package com.xxxy.dongyexuan.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.xxxy.dongyexuan.config.AlipayLocalConfig;
import com.xxxy.dongyexuan.mapper.IOrderMapper;
import com.xxxy.dongyexuan.mapper.IReservationMapper;
import com.xxxy.dongyexuan.mapper.IUserMapper;
import com.xxxy.dongyexuan.po.Order;
import com.xxxy.dongyexuan.po.Reservation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author zooy
 * @since 2024/6/26-22:14
 */
@Service
@Slf4j
public class PayService {

    @Autowired
    private AlipayLocalConfig alipayLocalConfig;

    @Autowired
    private IOrderMapper orderMapper;

    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private IReservationMapper reservationMapper;

    public String unifiedOrder(Order order) {

        AlipayClient alipayClient = getAlipayClient();

        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        // 设置商户门店编号
        model.setStoreId("NJ_001");

        // 设置订单标题
        model.setSubject("travel line 001");

        // 设置请求来源地址
        model.setRequestFromUrl("http://localhost:8080/springbootmt74k/front/index.html");

        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 设置PC扫码支付的方式
        // 走跳转模式
        model.setQrPayMode("2");

        // 设置订单绝对超时时间
        String expiryTime = LocalDateTime.now().plusSeconds(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        model.setTimeExpire(expiryTime);

        // 设置商户自定义二维码宽度
        model.setQrcodeWidth(150L);

        // 设置请求后页面的集成方式
        model.setIntegrationType("PCWEB");

        // 设置商户订单号
        model.setOutTradeNo(order.getOrderId());

        // 设置订单总金额
        model.setTotalAmount(String.valueOf(order.getTotalAmt()));

        request.setBizModel(model);

        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request, "POST");

            if (response.isSuccess()) {
                System.out.println("调用成功");
                String pageRedirectionData = response.getBody();
                // 进行订单生成
                order.setCreateTime(LocalDateTime.now());
                order.setUpdateTime(LocalDateTime.now());
                order.setRealAmt((int) (order.getTotalAmt() * 1.1));
                orderMapper.save(order);
                return pageRedirectionData;
            } else {
                System.out.println("调用失败");
                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // System.out.println(diagnosisUrl);
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        return null;

    }

    public void queryOrder(Order order) {

        // 初始化SDK
        AlipayClient alipayClient = getAlipayClient();

        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();

        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(order.getOrderId());
        request.setBizModel(model);

        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        System.out.println(response.getBody());

        orderMapper.updateQueryCount(order.getOrderId());

        if (response.isSuccess()) {
            System.out.println("调用成功");
            // 更新订单状态
            String tradeStatus = response.getTradeStatus();

            if (tradeStatus.equals("TRADE_SUCCESS")
                || tradeStatus.equals("TRADE_FINISHED")
            ) {
                order.setPayStatus(1);
                order.setPaySuccessTime(LocalDateTime.now());
                order.setUpdateTime(LocalDateTime.now());
                orderMapper.updateSuccessOrder(order);
                // 拆分为充值订单和消费订单
                if (order.getTransType() == 0) {
                    // 增加余额
                    userMapper.updateMoney(order.getRealAmt(), order.getUid());
                } else {
                    // 消费
                    // 直接更新为预约成功
                    reservationMapper.updateState(order.getRid());
                }

            }

        } else {
            System.out.println("调用失败");
            /*if (response.getCode().equals("40004")) {
                // 支付失败
                order.setPayStatus(2);
                order.setUpdateTime(LocalDateTime.now());
                order.setPayMsg(response.getSubMsg());
                orderMapper.updateFailureOrder(order);
            }*/
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }

    public void refundOrder(Order order) {

        // 初始化SDK
        AlipayClient alipayClient = getAlipayClient();

        // 构造请求参数以调用接口
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();

        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(order.getOrderId());
        // 设置退款金额
        model.setRefundAmount(String.valueOf(order.getTotalAmt() * 0.5));
        request.setBizModel(model);

        // 设置退款原因说明
        model.setRefundReason("取消预约");

        // 设置退款请求号
        model.setOutRequestNo(UUID.randomUUID().toString().replaceAll("-", ""));

        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

    }

    public AlipayClient getAlipayClient() {

        AlipayConfig alipayConfig = new AlipayConfig();
        //设置沙箱网关地址
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        //设置应用ID
        alipayConfig.setAppId(alipayLocalConfig.getAppId());
        //设置应用私钥
        alipayConfig.setPrivateKey(alipayLocalConfig.getPrivateKey());
        //设置请求格式，固定值json
        alipayConfig.setFormat("json");
        //设置字符集
        alipayConfig.setCharset("utf-8");
        //设置签名类型
        alipayConfig.setSignType("RSA2");
        //设置支付宝公钥
        alipayConfig.setAlipayPublicKey(alipayLocalConfig.getPublicKey());
        //实例化客户端
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(alipayConfig);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        return alipayClient;
    }
}
